package com.nulp.psycho.web.servlet;

import java.io.IOException;
import java.sql.Date;

import javax.mail.MessagingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.nulp.psycho.db.model.User;
import com.nulp.psycho.db.service.UserService;
import com.nulp.psycho.hash.MD5;
import com.nulp.psycho.mail.EmailUtility;

@WebServlet("/RegistrationServlet")
public class RegistrationServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

    public RegistrationServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	@SuppressWarnings("deprecation")
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		StringBuilder message = new StringBuilder();
		message.append("http://");
		message.append(request.getServerName() + ":");
		message.append(request.getServerPort());
		message.append(request.getContextPath());
		
		User user = new User();
		user.setRoleId(3);
		user.setConfirmationStatus(false);
		user.setLogin(request.getParameter("inputLogin"));
		user.setPassword(MD5.getHash(request.getParameter("inputPassword")));
		user.setEmail(request.getParameter("inputEmail"));
		user.setfName(request.getParameter("inputFName"));
		user.setlName(request.getParameter("inputLName"));
		user.setSex(request.getParameter("sex"));
		user.setBirthday(new Date(Integer.parseInt(request.getParameter("year"))-1900, Integer.parseInt(request.getParameter("month"))-1, Integer.parseInt(request.getParameter("day"))));
		UserService service = new UserService();
		
		service.create(user);
		
		message.append("/confirmAccount?hash=" + ((User) service.getUserByLogin(user.getLogin())).getHash());
		
		try {
			new EmailUtility().sendEmail("Confirm account", "Confirm your account" + "<a href='"+message+"'>CONFIRM</a>", user);
		} catch (MessagingException e) {
			e.printStackTrace();
		}
		
		request.getRequestDispatcher("home").forward(request, response);
	}

}
